package vip.zhenzicheng.concurrent_program.thread.sgg.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平/非公平锁展示demo 卖票
 *
 * @author zhenzicheng
 * @date 2022-06-23 11:12
 */
public class SaleTicketDemo {

  public static void main(String[] args) {
    Ticket ticket = new Ticket();

    new Thread(() -> {
      for (int i = 0; i < 55; i++) {
        ticket.sale();
      }
    }, "t1").start();

    new Thread(() -> {
      for (int i = 0; i < 55; i++) {
        ticket.sale();
      }
    }, "t2").start();

    new Thread(() -> {
      for (int i = 0; i < 55; i++) {
        ticket.sale();
      }
    }, "t3").start();
  }
}

class Ticket { // 资源类

  ReentrantLock lock = new ReentrantLock(true);
  private int number = 50;

  public void sale() {
    lock.lock();
    try {
      if (number > 0) {
        System.out.println(Thread.currentThread().getName() + "卖出第：" + number-- + "张，剩余：" + number);
      }
    } finally {
      lock.unlock();
    }
  }
}
